<template>
  <div>
    <h1>IndexedDB 双表管理</h1>
    <div class="tab-control">
      <button
        @click="activeTable = 'MyStore'"
        :class="{ active: activeTable === 'MyStore' }"
      >
        MyStore
      </button>
      <button
        @click="activeTable = 'CheckStore'"
        :class="{ active: activeTable === 'CheckStore' }"
      >
        CheckStore
      </button>
    </div>

    <div class="form-group">
      <input v-model="currentItem.a1" placeholder="输入a1字段" />
      <input v-model="currentItem.a3" placeholder="输入a3字段" />
      <button @click="saveItem">{{ isEditing ? "更新" : "添加" }}</button>
      <button v-if="isEditing" @click="cancelEdit">取消</button>
    </div>

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>A1</th>
          <th>A3</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in activeItems" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.a1 }}</td>
          <td>{{ item.a3 }}</td>
          <td>
            <button @click="editItem(item)">编辑</button>
            <button @click="deleteItem(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";

const DB_NAME = "MyDatabase";
const STORE_NAMES = {
  MY_STORE: "MyStore",
  CHECK_STORE: "CheckStore",
};
let db = null;

// 状态管理
const activeTable = ref(STORE_NAMES.MY_STORE);
const myStoreItems = ref([]);
const checkStoreItems = ref([]);
const currentItem = ref({ a1: "", a3: "" });
const isEditing = ref(false);
const editingId = ref(null);

// 初始化数据库
const initDB = () => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, 3); // 版本号升级

    request.onupgradeneeded = (event) => {
      const db = event.target.result;

      // 创建或升级MyStore表
      if (!db.objectStoreNames.contains(STORE_NAMES.MY_STORE)) {
        const store = db.createObjectStore(STORE_NAMES.MY_STORE, {
          keyPath: "id",
          autoIncrement: true,
        });
        store.createIndex("a1", "a1", { unique: false });
        store.createIndex("a3", "a3", { unique: false });
      }

      // 创建或升级CheckStore表
      if (!db.objectStoreNames.contains(STORE_NAMES.CHECK_STORE)) {
        const store = db.createObjectStore(STORE_NAMES.CHECK_STORE, {
          keyPath: "id",
          autoIncrement: true,
        });
        store.createIndex("a1", "a1", { unique: false });
        store.createIndex("a3", "a3", { unique: false });
      }
    };

    request.onsuccess = (event) => {
      db = event.target.result;
      initializeStores();
      resolve(db);
    };

    request.onerror = (event) => {
      console.error("数据库打开失败", event);
      reject("数据库打开失败");
    };
  });
};

// 初始化表数据
const initializeStores = async () => {
  await initializeStore(STORE_NAMES.MY_STORE, myStoreItems, [
    { a1: "MyStore数据1", a3: "类型A" },
    { a1: "MyStore数据2", a3: "类型B" },
    { a1: "MyStore数据3", a3: "类型C" },
  ]);

  await initializeStore(STORE_NAMES.CHECK_STORE, checkStoreItems, [
    { a1: "CheckStore验证1", a3: "测试A" },
    { a1: "CheckStore验证2", a3: "测试B" },
    { a1: "CheckStore验证3", a3: "测试C" },
  ]);
};

// 初始化单个表
const initializeStore = (storeName, itemsRef, initialData) => {
  return new Promise((resolve) => {
    const transaction = db.transaction(storeName, "readonly");
    const store = transaction.objectStore(storeName);
    const countRequest = store.count();

    countRequest.onsuccess = () => {
      if (countRequest.result === 0) {
        // 表为空，添加初始数据
        const writeTransaction = db.transaction(storeName, "readwrite");
        const writeStore = writeTransaction.objectStore(storeName);

        initialData.forEach((item) => {
          writeStore.add(item);
        });

        writeTransaction.oncomplete = () => {
          refreshItems(storeName, itemsRef);
          resolve();
        };
      } else {
        // 表已有数据，直接加载
        refreshItems(storeName, itemsRef);
        resolve();
      }
    };
  });
};

// 刷新表数据
const refreshItems = (storeName, itemsRef) => {
  const transaction = db.transaction(storeName, "readonly");
  const store = transaction.objectStore(storeName);
  const request = store.getAll();

  request.onsuccess = () => {
    itemsRef.value = request.result;
  };
};

const activeItems = computed(() => {
  return activeTable.value === STORE_NAMES.MY_STORE
    ? myStoreItems.value
    : checkStoreItems.value;
});

// 保存数据（添加或更新）
const saveItem = () => {
  if (!currentItem.value.a1 || !currentItem.value.a3) return;

  // const storeName = activeTable.value
  const storeName = "MyStore";
  const transaction = db.transaction(storeName, "readwrite");
  const store = transaction.objectStore(storeName);

  if (isEditing.value) {
    store.put({ ...currentItem.value, id: editingId.value });
  } else {
    store.add({ ...currentItem.value });
    const getAllRequest = store.getAll();
    getAllRequest.onsuccess = (event) => {
      let jsonstr = JSON.stringify(event.target.result, null, 2);
      alert(jsonstr);
    };
  }

  transaction.oncomplete = () => {
    resetForm();
    if (storeName === STORE_NAMES.MY_STORE) {
      //getAllItems(storeName, myStoreItems);
    } else {
      getAllItems(storeName, checkStoreItems);
    }
  };
};

// 编辑数据
const editItem = (item) => {
  currentItem.value = { a1: item.a1, a3: item.a3 };
  editingId.value = item.id;
  isEditing.value = true;
};

// 删除数据
const deleteItem = (id) => {
  if (!confirm("确定要删除这条记录吗？")) return;

  const storeName = activeTable.value;
  const transaction = db.transaction(storeName, "readwrite");
  const store = transaction.objectStore(storeName);
  store.delete(id);

  transaction.oncomplete = () => {
    if (storeName === STORE_NAMES.MY_STORE) {
      getAllItems(storeName, myStoreItems);
    } else {
      getAllItems(storeName, checkStoreItems);
    }
  };
};

// 取消编辑
const cancelEdit = () => {
  resetForm();
};

// 重置表单
const resetForm = () => {
  currentItem.value = { a1: "", a3: "" };
  isEditing.value = false;
  editingId.value = null;
};

onMounted(() => {
  initDB();
});
</script>

<style scoped>
.tab-control {
  margin-bottom: 20px;
}
.tab-control button {
  padding: 8px 16px;
  margin-right: 10px;
  cursor: pointer;
}
.tab-control button.active {
  background-color: #4caf50;
  color: white;
}
.form-group {
  margin-bottom: 20px;
}
input {
  margin-right: 10px;
  padding: 5px;
}
button {
  margin-right: 5px;
  padding: 5px 10px;
}
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}
th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
th {
  background-color: #f2f2f2;
}
</style>
